import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
import { publishPresets, users } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { Platform } from '@/types/platform-settings';

// 获取用户的所有预设
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({
        success: false,
        error: '请先登录',
      }, { status: 401 });
    }

    // 获取用户信息
    const user = await db.query.users.findFirst({
      where: eq(users.email, session.user.email),
    });

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '用户不存在',
      }, { status: 404 });
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const platform = searchParams.get('platform') as Platform | null;

    // 构建查询条件
    const whereCondition = platform 
      ? and(
          eq(publishPresets.userId, user.id),
          eq(publishPresets.platform, platform)
        )
      : eq(publishPresets.userId, user.id);

    // 获取用户的预设列表
    const presets = await db.query.publishPresets.findMany({
      where: whereCondition,
      orderBy: (presets, { desc }) => [desc(presets.isDefault), desc(presets.updatedAt)],
    });

    // 解析平台配置JSON
    const presetsWithParsedData = presets.map(preset => ({
      ...preset,
      platformConfig: preset.platformConfig ? JSON.parse(preset.platformConfig) : null
    }));

    return NextResponse.json({
      success: true,
      data: presetsWithParsedData,
    });
  } catch (error) {
    console.error('获取预设失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取预设失败',
    }, { status: 500 });
  }
}

// 创建新预设
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({
        success: false,
        error: '请先登录',
      }, { status: 401 });
    }

    // 获取用户信息
    const user = await db.query.users.findFirst({
      where: eq(users.email, session.user.email),
    });

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '用户不存在',
      }, { status: 404 });
    }

    const body = await request.json();
    const {
      name,
      platform = 'wechat',
      authorName,
      autoGenerateDigest = true,
      headerContent = '',
      footerContent = '',
      isDefault = false,
      platformConfig = null,
    } = body;

    // 如果设置为默认预设，先取消同平台其他预设的默认状态
    if (isDefault) {
      await db.update(publishPresets)
        .set({ isDefault: false })
        .where(and(
          eq(publishPresets.userId, user.id),
          eq(publishPresets.platform, platform)
        ));
    }

    // 创建新预设
    const presetId = createId();
    await db.insert(publishPresets).values({
      id: presetId,
      userId: user.id,
      name,
      platform,
      authorName,
      autoGenerateDigest,
      headerContent,
      footerContent,
      isDefault,
      platformConfig: platformConfig ? JSON.stringify(platformConfig) : null,
    });

    // 获取创建的预设
    const newPreset = await db.query.publishPresets.findFirst({
      where: eq(publishPresets.id, presetId),
    });

    return NextResponse.json({
      success: true,
      data: newPreset,
      message: '预设创建成功',
    });
  } catch (error) {
    console.error('创建预设失败:', error);
    return NextResponse.json({
      success: false,
      error: '创建预设失败',
    }, { status: 500 });
  }
}
